﻿using System;
using System.Collections.Generic;
using System.Threading;

namespace Sustainalytics.Synchronization.Interface
{
    public static class Retry
    {
        public static void Do(
            Action action,
            TimeSpan retryInterval,
            ILogger logger,
            int retryCount = 3)
        {
            Do<object>(() =>
            {
                action();
                return null;
            }, retryInterval, logger, retryCount);
        }

        public static T Do<T>(
            Func<T> action,
            TimeSpan retryInterval,
            ILogger logger,
            int retryCount = 3)
        {
            var exceptions = new List<Exception>();
            var callingMethodName = action.Target.ToString().Split('+')[0];
            for (int retry = 0; retry < retryCount; retry++)
            {
                try
                {
                    if (retry > 0)
                    {
                        logger.Log(string.Format(callingMethodName + " Retry number {0}, wait duration {1} (hh/mm/ss)", retry, retryInterval));
                        Thread.Sleep(retryInterval);
                    }
                    return action();
                }
                catch (Exception ex)
                {
                    logger.Log(ex.Message);
                    exceptions.Add(ex);
                }
            }

            throw new AggregateException(exceptions);
        }
    }
}